// ignore_for_file: unnecessary_null_comparison
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:jetour_line/aha_jetour_line.dart';
import 'package:jetour_line/base_widget/loading_widget.dart';
import 'package:jetour_line/map/map_utils.dart';
import 'package:jetour_line/models/public_msg_manger.dart';
import 'package:jetour_line/my_colors.dart';
import 'package:jetour_line/network/aha_http.dart';
import 'package:jetour_line/pages/creatTravel/creat_travel_page.dart';
import 'package:jetour_line/pages/home/guide_view.dart';
import 'package:jetour_line/pages/home/home_common_widget.dart';
import 'package:jetour_line/pages/home/home_head_widget.dart';
import 'package:jetour_line/pages/home/home_line_widget.dart';
import 'package:jetour_line/utils/aha_utils.dart';
import 'package:jetour_line/utils/extension_int.dart';
import 'package:jetour_line/utils/login_utils.dart';
import 'package:jetour_line/utils/page_push_utils.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import '../../base_widget/base_image.dart';
import '../../base_widget/base_scaffold.dart';
import '../../base_widget/my_refresh_view.dart';
import '../../base_widget/permission_alert.dart';
import '../../base_widget/sliver_list_widget.dart';
import '../../model/city_list_model.dart';
import '../../model/location_info_model.dart';
import '../../models/swiper_model.dart';
import '../../network/jetour_http.dart';
import "package:jetour_line/models/guide_list_model.dart" as user_guide;
import "package:jetour_line/models/line_list_model.dart" as line_list;

import '../../utils/permission_utils.dart';
import '../baseWidget/common_item_widget.dart';
import '../webview/webview_page.dart';

class AhaHomePageScreen extends StatefulWidget {
  const AhaHomePageScreen({Key? key}) : super(key: key);

  @override
  State<AhaHomePageScreen> createState() => _HomePageScreenState();
}

class _HomePageScreenState extends State<AhaHomePageScreen> {
  final MyRefreshViewController _controller = MyRefreshViewController();
  List<IndexSwiperModel> swiperData = [];
  List<user_guide.ListElement> userGuideList = [];
  List<line_list.ListElement> lineList = [];
  int type = 1; //1精选共创路书：type传入1  最新路书：type不传/传0
  int page = 1;
  int cityId = 0;
  String? cityName = '';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getBannerData();
    getUserGuideRecommendData();
    getLineList();
    PermissionUtils.requestLocationPermission(context, (bool isAgree) {
      if (isAgree) {
        MapUtils.getLocation((value) {
          if (value != null && cityName!.isEmpty) {
            LocationInfoModel model = value;
            cityName = model.component.city;
            cityId = model.component.cityId;
            getUserGuideRecommendData();
            getLineList();
            setState(() {});
          }
        });
      }
    });
    // AmapLocationFlutterPlugin.setApiKey(
    //     "28bd43ed17d636692c8803e9e0d246b2", "dfb64c0463cb53927914364b5c09aba0");

    String? jeTourTkoen = AhaManger().getToken();
    print(
        'jeTourTkoenjeTourTkoen$jeTourTkoen  uat = ${AhaManger().isUat} 1.1.0');
    if (jeTourTkoen != null &&
        jeTourTkoen.isNotEmpty &&
        PublicMsgManger().userInfoModel == null) {
      //进入页面前 传入token 并且未登录  执行登录
      LoginUtils.login(jeTourTkoen, (isLogin) {
        if (isLogin) {
          setState(() {});
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    bool showLoading = false;
    if (lineList.isEmpty && userGuideList.isEmpty && swiperData.isEmpty) {
      showLoading = true;
    } else {
      showLoading = false;
    }
    return Stack(
      children: [
        BaseScaffold(
            rightItemCallBack: () {},
            title: '捷途路书',
            body: showLoading
                ? const LoadingWidget()
                : SizedBox(
                    width: double.infinity,
                    height: double.infinity,
                    child: Stack(
                      alignment: Alignment.bottomCenter,
                      children: [
                        MyRefreshView(
                            refreshCallBack: (bool isUp) {
                              if (isUp) {
                                //下拉刷新
                                page = 1;
                              } else {
                                //上划加载更多
                                page++;
                              }
                              getUserGuideRecommendData();
                            },
                            controller: _controller,
                            child: CustomScrollView(
                              //页面复杂Listview
                              slivers: [

                                HomeHeadWidget(
                                  cityName: cityName!,
                                  swiperData: swiperData,
                                  callBack: (CityModel cityModel) {
                                    cityId = cityModel.id;
                                    print('cityIdcityIdcityIdcityId=$cityId');
                                    cityName = cityModel.name;
                                    // getBannerData();
                                    // getUserGuideRecommendData();
                                    getLineList();
                                    _controller.beginRef();
                                  },
                                ),
                                if (lineList.isNotEmpty)
                                  HomeCommonWidget(
                                    cityId: cityId,
                                    cityName: cityName,
                                    lineList: lineList,
                                    callBack: (index) {
                                      type = index;
                                      page = 1;
                                      getUserGuideRecommendData();
                                    },
                                  ),
                                if (userGuideList.isNotEmpty)
                                  SliverListWidget.getSliverList(
                                      userGuideList.length, (context, index) {
                                    return CommonItemWidget(
                                      comment: userGuideList[index],
                                    );
                                  })
                              ],
                            )),
                        GestureDetector(
                          onTap: () async { 
                            if (PublicMsgManger().userInfoModel == null) {
                              AhaManger manger = AhaManger();
                              if (manger.loginCallBack != null) {
                                manger.loginCallBack!((String token) {
                                  if (token.isNotEmpty) {
                                    LoginUtils.login(token, (bool isLogin) {
                                      if (isLogin) {
                                        PagePushUtils.push(
                                            context, CreatTravelScreen());
                                      }
                                    });
                                  }
                                });
                              }
                            } else {
                              PagePushUtils.push(context, CreatTravelScreen());
                            }
                          },
                          child: Padding(
                            padding: EdgeInsets.only(bottom: 24.px),
                            child: BaseImage(
                              image: 'home_btn_sao',
                              width: 140.px,
                              height: 140.px,
                            ),
                          ),
                        )
                      ],
                    ),
                  )),
        if (userGuideList.isNotEmpty) GuideViewWidget(),
      ],
    );
  }

  //主动下拉刷新 会执行refreshCallBack
  void startRef() {
    _controller.beginRef();
  }

  //结束下拉刷新
  void endRef() {
    _controller.refreshEnd();
  }

  //banner图
  void getBannerData() {
    JetourHttp().get(JetourRouter.IndexSwiperList).then((result) {
      print('json.encode(result)${json.encode(result)}');
      List<IndexSwiperModel> list = [];
      for (int i = 0; i < result.length; i++) {
        list.add(IndexSwiperModel.fromJson(result[i]));
      }
      setState(() {
        swiperData = list;
      });
    }).catchError((e) {});
  }

//共创行程数据
  void getUserGuideRecommendData() {
    Map<String, dynamic>? params = {};
    params['page'] = page;
    params['type'] = type;
    params['city'] = cityId;
    JetourHttp().get(JetourRouter.UserGuideList, params: params).then((result) {
      user_guide.UserGuideListModel data =
          user_guide.UserGuideListModel.fromJson(result);
      if (page == 1) {
        userGuideList.clear();
      }
      userGuideList.addAll(data.list);
      _controller.refreshEnd(page: page, maxPage: data.meta.maxPage);
      setState(() {});
    }).catchError((e) {});
  }

// 路书列表
  void getLineList() {
    Map<String, dynamic> params = Map();
    Map<String, dynamic> data = Map();
    if (cityId > 0) {
      data['stCity'] = cityId;
    }
    AhaHttp()
        .post(AhaRouter.lineList, params: params, data: data)
        .then((result) {
      line_list.LineListModel data = line_list.LineListModel.fromJson(result);
      if (page == 1) {
        lineList.clear();
      }
      setState(() {
        lineList.addAll(data.list);
      });
    }).catchError((e) {
      _controller.refreshEnd();
    });
  }
}
